package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.DecisionConsulting;
import com.gxuwz.stats.service.DecisionConsultingService;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/decisionConsulting")
public class DecisionConsultingController {

    @Autowired
    private DecisionConsultingService decisionConsultingService;

    @Autowired
    private UserService userService;

    /**
     * 分页查询决策咨询数据
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getConsultingList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            IPage<DecisionConsulting> page = new Page<>(currentPage, pageSize);
            QueryWrapper<DecisionConsulting> queryWrapper = new QueryWrapper<>();

            if (params.containsKey("keyword") && !params.get("keyword").isEmpty()) {
                String keyword = "%" + params.get("keyword") + "%";
                queryWrapper.and(wrapper -> wrapper
                        .like("consulting_result_name", keyword)
                        .or().like("consulting_category", keyword));
            }

            IPage<DecisionConsulting> resultPage = decisionConsultingService.getDecisionConsultingList(page, queryWrapper);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增决策咨询数据
     */
    @PostMapping("/add")
    public ResponseEntity<?> saveConsulting(@RequestBody DecisionConsulting decisionConsulting) {
        System.out.println("前端数据：" + decisionConsulting);

        // 1. 验证 username 是否存在
        String username = decisionConsulting.getUsername();
        if (username == null || username.isEmpty()) {
            return ResponseEntity.badRequest().body("用户名不能为空");
        }

        // 2. 根据 username 查询 user_id
        Integer userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            return ResponseEntity.badRequest().body("用户不存在");
        }
        System.out.println("获取到的 user_id：" + userId);

        // 3. 设置 user_id 并保存
        decisionConsulting.setUserId(userId);
        decisionConsulting.setConsultingId(null); // 确保主键自增
        boolean isSaved = decisionConsultingService.save(decisionConsulting);

        return isSaved ?
                ResponseEntity.status(HttpStatus.CREATED).build() :
                ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 批量删除决策咨询数据
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Void> deleteConsulting(@RequestBody List<Long> ids) {
        decisionConsultingService.removeByIds(ids);
        return ResponseEntity.noContent().build();
    }

    /**
     * 修改决策咨询数据
     */
    @PutMapping("/update/{id}")
    public ResponseEntity<Void> updateConsulting(
            @PathVariable("id") Long id,
            @RequestBody DecisionConsulting decisionConsulting
    ) {
        decisionConsulting.setConsultingId(id);
        decisionConsultingService.updateById(decisionConsulting);
        return ResponseEntity.ok().build();
    }
}